package com.atguigu.jucdemo.util;

import java.util.Random;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {
    public static void main(String[] args) {
        //占车位,三个车位
        Semaphore semaphore = new Semaphore(3);

        for (int i = 1; i <= 5; i++) {
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"占到了车位");
                    TimeUnit.SECONDS.sleep(new Random().nextInt(3)+1);
                    System.out.println(Thread.currentThread().getName()+"离开停车场");
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }finally {
                    semaphore.release();
                }
            },String.valueOf(i)+"号汽车").start();
        }
    }
}
